<template>
  <div>
    <Row class="list_row" style="margin-top: 0px;;min-height: 400px;">
      <Row style="margin: 5px 0px 10px 0px;">
        <Select v-model="selTrainCenterId" filterable clearable :placeholder="$t('common.trainSePlaceTips')"
                style="width: 200px;margin-right: 20px"
                v-show="isCanChooseTc">
          <Option v-for="tc in trainCenterList" :value="tc.id" :key="tc.id">{{tc.name}}</Option>
        </Select>
        <Input v-model="searchKeyword" :placeholder="$t('common.snPlaceTips')" style="width: 200px;margin-right: 20px"/>
        <Button  class="btnWhite" type="primary" icon="ios-search" style="margin-right: 20px" @click="search">{{$t('search')}}</Button>
        <!-- 此处权限修改为：训练中心无权限，仅超级管理员可新增、修改、删除 -->
        <Button  class="btnWhite" type="primary" icon="md-add" @click="showAddModal" v-if="roleId == '1'">{{$t('deviceP.addDevice')}}</Button>
      </Row>
      <Table :columns="deviceColumn" border :data="dataList" stripe :no-data-text="noDataMsg">
        <template slot-scope="{ row, index }" slot="seq">
          {{(currentPage - 1) * pageSize + index + 1}}
        </template>
        <template slot-scope="{ row, index }" slot="status">
          <span v-if="row.onlineStatus == 1" style="color:#2d8cf0">{{$t('common.online')}}</span>
          <span v-else>{{$t('common.outline')}}</span>
        </template>
      </Table>
      <div class="div_page">
        <Page :total="totalCount" :current="currentPage" :page-size="pageSize"
              show-total show-elevator prev-text="<" next-text=">" @on-change="pageChg"/>
      </div>
    </Row>

    <!-- 新增设备弹窗 -->
    <Modal v-model="entityModelVisiable" :mask-closable="false" width="500" :title="entityModelTitle" mask>
      <Form ref="entityFormRef" :model="entityForm" :rules="addFormRules" :label-width="120">
        <FormItem :label="$t('common.traninerCenter')" prop="trainCenterId" v-show="isCanChooseTc && entityForm.opeType == 'add'">
          <Select v-model="entityForm.trainCenterId" filterable :placeholder="$t('common.trainSePlaceTips')" >
            <Option v-for="tc in trainCenterList" :value="tc.id" :key="tc.id">{{tc.name}}</Option>
          </Select>
        </FormItem>
        <FormItem :label="$t('common.deviceName')"  prop="name">
          <Input v-model="entityForm.name" :placeholder="$t('common.deviceNamePlaceTips')"></Input>
        </FormItem>
        <FormItem :label="$t('common.deviceSeq')" prop="sn">
          <Input v-model="entityForm.sn" :placeholder="$t('common.seqPlaceTips')"></Input>
        </FormItem>
      </Form>
      <div slot="footer" style="text-align: center">
        <Button @click="entityModelVisiable=false">{{$t('cancel')}}</Button>
        <Button type="primary" @click="saveOrUpdate" :loading="saveLoading" style="margin-left: 15px">
          <span v-if="!saveLoading">{{$t('save')}}</span>
          <span v-else>{{$t('save')}}....</span>
        </Button>
      </div>
    </Modal>
    <!-- 运动记录弹窗 -->
    <Modal v-model="sportsRecordModelVisiable" :mask-closable="false" width="100" :title="sportsModalTitle"
           :fullscreen="true" :scrollable="true">
      <div>
        <Row class="list_row" style="margin-top: 0px">
          <Row class="flex  " style="margin: 5px 0px 10px 0px;">
            <div class="box" >
              <Date-picker format="yyyy-MM-dd" type="date" v-model="startQueryDate" placement="bottom-end"
                         :placeholder="$t('common.startTimePlaceTips')" clearable style="width: 200px"
                         @on-change="startDateChange"></Date-picker>
            <span style="margin-left: 10px;margin-right: 10px;">-</span>
            <Date-picker format="yyyy-MM-dd" type="date" v-model="endQueryDate" placement="bottom-end"
                         :placeholder="$t('common.endTimePlaceTips')" clearable style="width: 200px"
                         @on-change="endDateChange"></Date-picker>
            <Button  class="btnWhite" type="primary" icon="ios-search" style="margin-left: 20px" @click="searchSportsRecords">{{this.$t('search')}}</Button>
            <Button  class="btnWhite" icon="md-refresh" style="margin-left: 20px" @click="reset(true)">{{this.$t('reset')}}</Button>

            </div>

          </Row>
          <Table :columns="sportsRecordColumn" border :data="sportsRecordDataArr" stripe style="min-height: 278px;">
            <template slot-scope="{ row, index }" slot="seq">
              {{(currentPage - 1) * pageSize + index + 1}}
            </template>
          </Table>
          <div class="div_page">
            <Page :total="sportsRecordTotalCount" :current="sportsRecordCurrentPage"
                  :page-size="sportsRecordCountPageSize"
                  show-total show-elevator prev-text="<" next-text=">" @on-change="sportsRecordPageChg"/>
          </div>
        </Row>
      </div>
      <div slot="footer" style="text-align: center">
        <Button @click="reset(false)">{{this.$t('cancel')}}</Button>
      </div>
      <div slot="close" style="text-align: center">
        <i class="ivu-icon ivu-icon-ios-close" @click="reset(false)" ></i>
      </div>
    </Modal>
  </div>
</template>
<script>
import TrainCenterApi from '@/api/trainCenterApi'
import DeviceApi from '@/api/deviceApi'
import { isEmpty, copyObj } from '@/libs/util'
import stopIcon from '@/assets/images/end_.png'
import startIcon from '@/assets/images/start_.png'
import AnalysisReportApi from '@/api/analysisReportApi'
import { mapActions } from 'vuex'
export default {
  data () {
    return {
      roleId: '',
      saveLoading: false,
      searchKeyword: '',
      noDataMsg:  this.$t('common.noData'),
      entityModelTitle: this.$t('deviceP.addDevice'),
      isCanChooseTc: false,
      selTrainCenterId: '',
      trainCenterList: [],
      entityModelVisiable: false,
      entityForm: {
        id: '',
        name: '',
        sn: '',
        trainCenterId: ''
      },
      addFormRules: {
        trainCenterId: [
          { required: true, message: this.$t('common.trainMustTips'), trigger: 'blur' }
        ],
        name: [
          { required: true, message: this.$t('common.nameMustTips'), trigger: 'blur' },
          { type: 'string', max: 32, message: this.$t('common.namelenLow32Tips'), trigger: 'blur' }
        ],
        sn: [
          { required: true, message: this.$t('common.snMustTips'), trigger: 'blur' },
          { type: 'string', max: 64, message: this.$t('common.namelenLow64Tips'), trigger: 'blur' }
        ]
      },
      showDeviceLoading: false,
      totalCount: 20,
      currentPage: 1,
      pageSize: 10,
      dataList: [],
      deviceColumn: [
        {
          title: this.$t('common.seq'), 
          slot: 'seq',
          render: (h, params) => {
            return h('span', {
              class: 'sortBlock'
            }, params.index + 1)
          }
        },
        {
          title:this.$t('common.deviceName'),
          key: 'name'
        },
        {
          title:this.$t('common.deviceSeq'),
          key: 'sn'
        },
        {
          title:this.$t('common.lineStatus'),
          slot: 'status'
        },
        {
          title:this.$t('common.usedDuration'),
          key: 'usedDuration'
        },
        {
          title:this.$t('common.traninerCenter'),
          key: 'trainCenterName'
        },
        {
          
          title:this.$t('common.createTime'),
          key: 'createTime'
        },
        {
          
          title:this.$t('common.optColumn'),
          key: 'action',
          width: 250,
          render: (h, params) => {
            return h('div', [
              h('Button', {
                props: {
                  type: 'info',
                  size: 'small'
                },
                class: 'btnBlue',
                style: {
                  marginRight: '15px'
                },
                on: {
                  click: () => {
                    this.showSportsRecordModal(params.row.id, params.row.name)
                  }
                } 
              },  this.$t('common.useReportBtn')),
              h('Button', {
                props: {
                  type: 'warning',
                  size: 'small'
                },
                class: 'btnYellow',
                style: {
                  marginRight: '15px',
                  display: (this.roleId == '1') ? 'inline' : 'none'
                },
                on: {
                  click: () => {
                    this.showEditModal(params.row)
                  }
                }
              },  this.$t('common.editBtn')),
              h('Button', {
                props: {
                  type: 'error',
                  size: 'small'
                },
                style: {
                  display: (this.roleId == '1') ? 'inline' : 'none'
                },
                class: 'btnRed',
                on: {
                  click: () => {
                    this.del(params.row)
                  }
                } 
              },  this.$t('common.deleteBtn')),
            ])
          }
        }],

      selDeviceId: '',
      sportsModalTitle: '',
      sportsRecordDataArr: [],
      sportsRecordTotalCount: 0,
      sportsRecordCurrentPage: 1,
      sportsRecordCountPageSize: 10,
      sportsRecordModelVisiable: false,
      startQueryDate: '',
      endQueryDate: '',
      startQueryDateVal: '',
      endQueryDateVal: '',
      sportsRecordColumn: [
        {
          title: this.$t('common.seq'), 
          slot: "seq",
          width: '110',
          render: (h, params) => {
            return h('span', {
              class: 'sortBlock'
            }, params.index + 1)
          }
        },
        {
          title: this.$t('common.avatar'), 
          key: 'avatar',
          render: (h, params) => {
            // return h('strong', params.row.avatar)
            if (!params.row.avatar) {
              return h("div", {
                    class: "avatorBox",
                  },
            )
            }
            return h('img', {
              style: { // 样式
                'width': '20px',
                'border': '1px solid'
              },
              attrs: {
                src: params.row.avatar
              },
              on: {
                click: () => { this.showBigImg(params.row.avatar) }
              }

            })
          }
        },
        {
          title: this.$t('common.trainerName'), 
          key: 'trainerName'
        },
        {
          title: this.$t('common.planName'), 
          key: 'planName'
        },
        {
          title: this.$t('common.courseName'), 
          key: 'courseName'
        },
        {
          title: this.$t('common.trainActionColumn'), 
          key: 'trainActionName'
        },
        {
          title: this.$t('common.sportStartColumn'), 
          key: 'startTrainTime',
          render: (h, params) => {
            return h('div', {
              domProps: {
                innerHTML: `${params.row.startTrainTime}`
              }

            })
          }
        },
        {
          title: this.$t('common.sportEndColumn') , 
          key: 'endTrainTime',
          render: (h, params) => {
            return h('div', {
              domProps: {
                innerHTML: `${params.row.endTrainTime}`
              }

            })
          }
        },
        {
          title: this.$t('common.optColumn') ,
          key: 'action',
          width: 180,
          render: (h, params) => {
            return h('div', [
              // h('Button', {    ----TO DO移到分析报告里做
              //   props: {
              //     type: 'info',
              //     size: 'small'
              //   },
              //   style: {
              //     marginRight: '15px'
              //   },
              //   on: {
              //     click: () => {
              //       this.playVideo(params.row)
              //     }
              //   }
              // }, '播放视频'),
              h('Button', {
                props: {
                  type: 'info',
                  size: 'small'
                },
                style: {
                  marginRight: '15px'
                },
                class: 'btnBlue',
                on: {
                  click: () => {
                    this.viewAnalysis(params.row)
                  }
                }
              }, this.$t('common.analysisBtn') )
            ])
          }
        }
      ]
    }
  },
  created () {
    this.initFunc()
  },
  mounted () {
    this.getUserInfo().then(res => {
      this.roleId = res.roleId
    })
  },
  methods: {
    ...mapActions([
      'getUserInfo'
    ]),

    initFunc () {
      TrainCenterApi.userTrainCenterScope().then(res => {
        const data = res.data.data
        if (data.canSelect == '1') {
          this.isCanChooseTc = true
          this.trainCenterList = []
          if (data.list.length > 0) {
            for (var i = 0; i < data.list.length; i++) {
              var tc = data.list[i]
              this.trainCenterList.push(tc)
            }
          }
          this.selTrainCenterId = ''
        } else {
          this.selTrainCenterId = data.trainCenterId
        }
        this.search()
      }, error => {
        this.$Message.error(error.response.data.msg)
      })
    },
    search () {
      this.currentPage = 1
      this.fetchDataList()
    },
    fetchDataList () {
      this.noDataMsg = this.$t('common.loading')
      this.dataList = []
      var param = { 'pageSize': this.pageSize, 'currentPage': this.currentPage }
      if (this.selTrainCenterId) {
        param.trainCenterId = this.selTrainCenterId
      }
      if (this.searchKeyword) {
        param.name = this.searchKeyword
      }
      DeviceApi.pageResult(param).then(res => {
        this.dataList = res.data.data.pageResult.items
        this.totalCount = res.data.data.pageResult.totalCount
        this.noDataMsg = this.$t('common.noData') 
      }, error => {
        this.$Message.error(error.response.data.msg)
      })
    },
    showAddModal () {
      this.$refs.entityFormRef.resetFields()
      this.entityForm = {
        id: '',
        name: '',
        sn: '',
        trainCenterId: ''
      }
      // 不可选的，直接设置trainCenterId
      if (!this.isCanChooseTc) {
        this.entityForm.trainCenterId = this.selTrainCenterId
      }
      this.entityForm.opeType = 'add'
      this.entityModelTitle = this.$t('deviceP.addDevice')
      this.entityModelVisiable = true
    },
    showEditModal (row) {
      this.entityForm.opeType = 'edit'
      this.$refs.entityFormRef.resetFields()
      this.entityModelVisiable = true
      this.entityModelTitle = this.$t('deviceP.editDevice') 
      this.entityForm = copyObj(row)
    },
    saveOrUpdate () {
      this.$refs.entityFormRef.validate((valid) => {
        if (valid) {
          this.saveLoading = true
          // if (this.entityForm.id == '') {
          //   this.entityForm.trainCenterId = this.selTrainCenterId
          // }
          DeviceApi.saveOrUpdate(this.entityForm).then(response => {
            this.saveLoading = false
            if (this.entityForm.id == '') {
              this.$Message.success(this.$t('devideP.addDeviceSuc'))
            } else {
              this.$Message.success(this.$t('common.editSuc'))
            }
            this.$refs.entityFormRef.resetFields()
            this.entityModelVisiable = false
            this.fetchDataList()
          }, error => {
            this.saveLoading = false
            this.$Message.error(error.response.data.msg)
          })
        }
      })
    },
    pageChg (selPage) {
      this.currentPage = selPage
      this.fetchDataList()
    },
    del (row) {
      this.$Modal.confirm({
        title: this.$t('common.dDeleteTitleConfirm'),
        content: this.$t('common.DdeleteCt'),
        okText: this.$t('common.deleteBtn'),
        cancelText: this.$t('cancel'),
        onOk: () => {
          this.doDel(row.id)
        }
      })
    },
    doDel (id) {
      DeviceApi.delete(id).then(res => {
        this.$Message.success(this.$t('common.deleteSuc'))
        this.fetchDataList()
      }, error => {
        this.$Message.error(error.response.data.msg)
      })
    },
    // 重置查询
    reset (isOpen) {
      this.sportsRecordModelVisiable = isOpen,
      this.sportsRecordDataArr = []
      this.startQueryDate = ''
      this.startQueryDateVal = ''
      this.endQueryDate = ''
      this.endQueryDateVal = ''
      if (isOpen) {
        this.searchSportsRecords()
      }
    },
    showSportsRecordModal (id, name) {
      this.sportsModalTitle = this.$t('deviceP.recordP')+ name
      this.selDeviceId = id
      this.sportsRecordModelVisiable = true
      this.sportsRecordCurrentPage = 1
      this.searchSportsRecords()
    },
    searchSportsRecords () {
      this.sportsRecordDataArr = []
      var param = {
        'currentPage': this.sportsRecordCurrentPage,
        'pageSize': this.sportsRecordCountPageSize,
        'deviceId': this.selDeviceId
      }
      if (this.startQueryDateVal.length > 0) {
        param.startQueryDate = this.startQueryDateVal
      }
      if (this.endQueryDateVal.length > 0) {
        param.endQueryDate = this.endQueryDateVal
      }
      AnalysisReportApi.querySportsRecordPageResult(param).then(res => {
        this.sportsRecordDataArr = res.data.data.items
        this.sportsRecordTotalCount = res.data.data.totalCount
      }, error => {
        this.$Message.error(error.response.data.msg)
      })
    },
    sportsRecordPageChg (selPage) {
      this.sportsRecordCurrentPage = selPage
      this.searchSportsRecords()
    },
    startDateChange (formatTime) {
      this.startQueryDateVal = formatTime
    },
    endDateChange (formatTime) {
      this.endQueryDateVal = formatTime
    },
    playVideo (row) {
      const routeData = this.$router.resolve({
        name: 'video',
        query: { sportsRecordId: row.id }
      })
      window.open(routeData.href, '_blank')
    },
    viewAnalysis (row) {
      const routeData = this.$router.resolve({
        name: 'groupReport',
        query: { id: row.id }
      })
      window.open(routeData.href, '_blank')
    },
    startDateChange (formatTime) {
      this.startQueryDateVal = formatTime
    },
    endDateChange (formatTime) {
      this.endQueryDateVal = formatTime
    }
  }
}
</script>
<style>

.avatorBox{
  background:url('../../assets/images/icon_tx_boy.png');
  background-size:contain;
  width:20px;
  height:20px;
  margin:5px;
  margin-left:0
}
</style>
